package com.pure.common.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.pure.common.pojo.AccountReq;
import com.pure.common.pojo.OmsProductMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: json util
 * @date: 2022-06-25 20:56
 * @since 1.2.0
 **/
@Slf4j
public class PureJsonUtils {

    public static void main(String[] args) {

        AccountReq accountReq = new AccountReq();
        List<OmsProductMessage> list = new ArrayList<>();
        OmsProductMessage e = new OmsProductMessage();
        e.setMaterialName("冠心舒通胶囊-0.3g×60粒 0.3g×60粒 200盒/件");
        e.setDiscountType("");
        list.add(e);
        accountReq.setOmsProductMessageList(list);

        String str = JSON.toJSONString(accountReq);
        log.info("java object to json string is {}", str);

        JSONObject formData = JSONObject.parseObject(str);
        JSONArray omsProductMessageList = formData.getJSONArray("omsProductMessageList");
        if (omsProductMessageList != null) {
            for (int i = 0; i < omsProductMessageList.size(); i++) {
                JSONObject productMsg = omsProductMessageList.getJSONObject(i);
                if (productMsg != null) {
                    String discountType = productMsg.getString("discountType");
                    log.info("discountType string is {}", discountType);
                    if (StringUtils.isBlank(discountType)) {
                        productMsg.put("discountType", null);
                    }
                }
            }
            formData.put("omsProductMessageList", omsProductMessageList);
        }

        String s = JSONObject.toJSONString(formData, SerializerFeature.WriteMapNullValue);

        log.info("formData to json string is {}", s);
        JSONObject formDataNew = JSONObject.parseObject(s);
        AccountReq accountReqNew = JSON.toJavaObject(formDataNew, AccountReq.class);
        log.info("new object is {}", accountReqNew);
    }


}
